<?php
if($_SESSION['formula']!=1){
	echo "Akses tidak diizinkan";
	exit();
}
$act = filter($_GET['act']);
$field = filter($_GET['field']);
$q = filter($_GET['q']);

if(empty($act)){	
?>		
					<!-- box / title -->
					<div class="title">
						<h5>Data Formula Produksi</h5>								
						<div class="search global-nav">
							<form method="GET" class="form-search js-search-form" action="index.php?pages=formula" id="global-nav-search" style="width:350px">
								<input type="hidden" name="pages" value="formula">
								<select name="field" id="birthday_month" aria-label="Month" class="" >
									<option value="" <?php echo ($field=="")?"selected":"";?>>Cari Berdasarkan:</option>
									<option value="kode" <?php echo ($field=="kode")?"selected":"";?>>Kode Formula</option>
									<option value="nama" <?php echo ($field=="nama")?"selected":"";?>>Nama Formula</option>	
									<option value="type" <?php echo ($field=="type")?"selected":"";?>>Jenis Formula</option>									
								</select>

				            	<label class="visuallyhidden" for="search-query">Search query</label>
				            	<input class="search-input" type="text" id="search-query" placeholder="Search" name="q" value="<?php echo $q;?>">
				            	<span class="search-icon js-search-action">
				              		<button type="submit" class="icon nav-search" tabindex="-1">
				              			<span class="visuallyhidden">Search</span>
				              		</button>
				            	</span>
				            	<input disabled="disabled" class="search-input search-hinting-input" type="text" id="search-query-hint" autocomplete="off" spellcheck="false">				              					              
							</form>
						</div>
					</div>
					<!-- end box / title -->
					<div class="table">										
						<table>
							<thead>
								<tr>
									<th class="selected"><input type="checkbox" class="checkall" /></th>
									<th class="action">No.</th>
									<th class="left">Kode Formula</th>
									<th class="left">Nama </th>
									<th class="left">Jenis Formula </th>
									<th>Satuan Terkecil</th>
									<th>Satuan Per Karton</th>
									<th class="left">Keterangan</th>									
									<th class="action" colspan="2"><a href="?pages=formula&act=edit" class="icon-plus-sign" title="Tambah Data Baru"></a></th>									
								</tr>
							</thead>
							<tbody>
							<?php			

							$q2=$q;

							$addQuery='';

							if(!empty($field))
								$addQuery .= " WHERE $field LIKE '%$q2%' ";

							$batas=10;
							$pg=(int) $_GET['pg'];
							if(empty($pg))
							{
								$posisi=0;
								$pg=1;
							}
							else
							{
								$posisi = ($pg-1) * $batas;
							}
							$sqlSup1 = mysql_query("SELECT * FROM tb_formula $addQuery ORDER BY id_formula DESC LIMIT $posisi, $batas");
							
							$no=$posisi+1;
							while($dataSup = mysql_fetch_array($sqlSup1)){								

								//$status = ($dataSup['status']==1)? "Aktif":"Non Aktif";
							?>
								<tr>
									<td class="selected"><input type="checkbox" /></td>
									<td class="center"><?php echo $no;?></td>
									<td><?php echo $dataSup['kode'];?></td>
									<td><?php echo $dataSup['nama'];?></td>
									<td><?php echo $dataSup['type'];?></td>
									<td><?php echo $dataSup['satuan_terkecil'];?> KARTON</td>
									<td><?php echo $dataSup['satuan_per_karton'];?> CUP</td>
									<td><?php echo $dataSup['ket'];?></td>					
									<td class="action"><a href="?pages=formula&act=edit&id=<?php echo $dataSup['id_formula'];?>" class="icon-edit" title="Ubah Data"></a></td>
									<td class="action">
										<a href="#" title="Hapus Data" onClick="if(confirm('Anda akan menghapus data ini?')) window.location='?pages=formula&act=del&id=<?php echo $dataSup['id_formula'];?>';" class="icon-trash"></a>
									</td>								
								</tr>
							<?php	
								$no++;				
							}

							$sqlSup2 = mysql_query("SELECT * FROM tb_formula $addQuery ORDER BY id_formula DESC");
							$jumlahData = mysql_num_rows($sqlSup2);

							$file="?pages=formula&field=$field&q=$q";
							$jmlhalaman=ceil($jumlahData/$batas);
	
							?>															
							</tbody>
						</table>
						<!-- pagination -->
						<div class="pagination pagination-left">
							<div class="results">
								<span><?php echo "Showing Results ".($posisi+1)."-".($no-1)." of $jumlahData";?></span>
							</div>
							<ul class="pager">
								<?php
								//link ke halaman sebelumnya (previous)
								if($pg > 1){
									$previous=$pg-1;
									echo "<li><a href=$file&pg=1>&laquo; First</a></li>
									<li><a href=$file&pg=$previous>&laquo; Prev</a></li> ";
								}else{ 
									echo "<li class='disabled'>&laquo; First</li>
									<li class='disabled'>&laquo; Prev</li> ";
								}
								?>

								<?php
								//Link untuk Angka
								$angka=($pg > 3 ? " <li class='separator'>...</li> " : " ");
								for($i=$pg-2;$i<$pg;$i++)
								{
								  if ($i < 1) 
								      continue;
								  $angka .= "<li><a href='$file&pg=$i'>$i</a></li> ";
								}

								$angka .= " <li class='current'>$pg</li>";
								for($i=$pg+1;$i<($pg+3);$i++)
								{
								  if ($i > $jmlhalaman) 
								      break;
								  $angka .= "<li><a href='$file&pg=$i'>$i</a></li> ";
								}

								$angka .= ($pg+2<$jmlhalaman ? " <li class='separator'>...</li> <li><a href='$file&pg=$jmlhalaman'>$jmlhalaman</a></li>" : " ");

								echo "$angka";
								?>
								

								<?php
								//link kehalaman berikutnya (Next)
								if($pg < $jmlhalaman)
								{
									$next=$pg+1;
									echo "<li><a href='$file&pg=$next'>Next &raquo;</a></li>
									<li><a href='$file&pg=$jmlhalaman'>Last &raquo;</a></li>";
								}
								else
								{ 
									echo "<li class='disabled'>Next &raquo;</li>
									<li class='disabled'>Last &raquo;</li> ";
								}		
								?>													
							</ul>
						</div>

						<!-- end pagination -->
						<!-- table action -->
						
						<!-- end table action -->						
					</div>

<?php
}elseif ($act=='edit') {

	$id_formula = (int) filter($_GET['id']);

	$sqlSup = mysql_query("SELECT * FROM tb_formula WHERE id_formula=$id_formula");
	$dataSup = mysql_fetch_array($sqlSup);
	$type = ($dataSup['type']==RTS)? "RTS":"RTU";

	if(!empty($id_formula)){
		?>
		<!-- box / title -->
		<div class="title">
			<h5>Ubah Data Formula</h5>														
		</div>
		<!-- end box / title -->
		<?php
	}else{
		?>
		<!-- box / title -->
		<div class="title">
			<h5>Tambah Data Formula</h5>														
		</div>
		<!-- end box / title -->
		<?php
	}
?>

	<div class="table">
		<form method="POST" action="?pages=formula&act=update">
		<input type="hidden" name="id_formula" value="<?php echo $dataSup['id_formula'];?>">
		<table style="width:auto;display:inline">
		   	<tbody>
		   		<tr>
					<td><label>Kode Formula</label></td>
					<td>:</td>
					<td><input type="text" value="<?php echo $dataSup['kode'];?>" size="60" name="kode" id="kode" placeholder="Kode Formula" required></td>
			   	</tr>
			   	<tr>
					<td><label>Nama Formula</label></td>
					<td>:</td>
					<td><input type="text" value="<?php echo $dataSup['nama'];?>" size="60" name="nama" id="nama" placeholder="Nama Formula" required></td>
			   	</tr>
			   	<tr>
					<td><label>Jenis Formula</label></td>
					<td>:</td>
					<td>
					<input type="text" value="RTS" size="60" name="type" id="type" placeholder="RTS" readonly="readonly">
					</tr>
			   	<tr>
					<td><label>Satuan Terkecil</label></td>
					<td>:</td>
					<td><input type="text" value="<?php echo $dataSup['satuan_terkecil'];?>" size="30" name="satuan_terkecil" id="satuan_terkecil" placeholder="Satuan Terkecil" required> KARTON</td>
			   	</tr>
			   	<tr>
					<td><label>Satuan Per Karton</label></td>
					<td>:</td>
					<td><input type="text" value="<?php echo $dataSup['satuan_per_karton'];?>" size="30" name="satuan_per_karton" id="satuan_per_karton" placeholder="Satuan Per Karton" required> CUP</td>
			   	</tr>
			   	<tr>
					<td style="vertical-align: top;"><label>Keterangan</label></td>
					<td style="vertical-align: top;">:</td>
					<td><textarea name="ket" id="ket" placeholder="Keterangan" style="width:389px;height:80px"><?php echo $dataSup['ket'];?></textarea></td>
			   	</tr>			   	
			 	<tr>
			 		<td>&nbsp;</td>
			 		<td>&nbsp;</td>
			 		<td>
			 			<input type="hidden" value="" size="15" name="id">
						<input type="submit" value="Simpan" name="submit" class="btn btn-primary">
						<input type="Reset" value="Reset" class="btn">
			 		</td>
		   		</tr>
		 	</tbody>
		</table>
		<table style="width:auto;display:inline;margin-left:20px">
		   	<tbody>
		   		<tr>
					<th class="action"><button class="icon-plus-sign" id="add_formula" title="Tambah Data Baru"></button></th>
					<th><label><b>Detail Formula</b></label></th>					
			   	</tr>
			   	<tr>
			   		<td colspan="2">
			   			<?php			   			
			   			$sqlDetail = mysql_query("SELECT * FROM tb_formula_detail WHERE id_formula='".$dataSup[id_formula]."'");
			   			$ono = mysql_num_rows($sqlDetail);
			   			if(!$ono){
			   				?>
			   				<div id="detail_formula" class="tabelDetail">
					   			<table style="width:600px;">
									<tbody>
								   		<tr>
											<td><label>Kode B.Baku</label></td>	
											<td><label>Jumlah</label></td>															
											<td rowspan="2" style="vertical-align:middle"><button class="icon-minus-sign" title="Hapus Data" onClick="deleteAddress(this);return false" ></button></td>
									   	</tr>
									   	<tr>
											<td>
												<select name="kode_bb[]" id="kode_bb" style="width:212px" data-placeholder="Pilih Bahan Baku" class="chzn-select">
													<?php
													$sqlBB = mysql_query("SELECT kode,nama FROM tb_kode_bb GROUP BY kode");
													while ($dataBB = mysql_fetch_array($sqlBB)) {
														echo "<option value='".$dataBB['kode']."'>".$dataBB['kode']."=>".$dataBB['nama']."</option>";
													}
													?>
												</select>
											</td>				
											<td><input type="text" size="30" name="jumlah[]" id="jumlah" placeholder="Jumlah Bahan Baku" required></td>
									   	</tr>
									  
									</tbody>
								</table>

							</div>
			   				<?php
			   			}else{
			   				$y==0;
			   				while ($dataDetail = mysql_fetch_array($sqlDetail)) {
			   					$kode_bb = $dataDetail['kode_bb'];
			   					$y++;
			   					?>
			   					<div id="detail_formula" class="tabelDetail">
					   			<table style="width:600px;">
									<tbody>
								   		<tr>
											<td><label>Kode B.Baku</label></td>					
											<td><label>Jumlah</label></td>	
											<td rowspan="2" style="vertical-align:middle"><a class="icon-minus-sign" title="Hapus Data" onClick="if(confirm('Anda akan menghapus data ini?')) window.location='?pages=formula&act=delDetail&id=<?php echo $dataDetail['id_formula_detail'];?>&id2=<?php echo $dataSup['id_formula'];?>';" ></a></td>
									   	</tr>
									   	<tr>
											
											<td>
												<input type="hidden" name="id_formula_detail[]" value="<?php echo $dataDetail['id_formula_detail'];?>">
												<select name="kode_bb[]"  style="width:212px" id="chzn-selectx<?php echo $y;?>">
													<?php
													$sqlBB = mysql_query("SELECT kode,nama FROM tb_kode_bb GROUP BY kode");
													while ($dataBB = mysql_fetch_array($sqlBB)) {
														if($kode_bb==$dataBB['kode']){
															$selected = " selected ";
														}else{
															$selected = " ";
														}

														echo "<option value='".$dataBB['kode']."' $selected>".$dataBB['kode']."=>".$dataBB['nama']."</option>";
													}
													?>
												</select>
											</td>				
											<td><input type="text" size="30" value="<?php echo $dataDetail['jumlah'];?>" name="jumlah[]" id="jumlah" placeholder="Jumlah Bahan Baku" required></td>
									   	</tr>
									   	
									</tbody>
								</table>
								</div>
								<script type="text/javascript">
								$(document).ready(function () {
																		 
									$("#chzn-selectx<?php echo $y; ?>").chosen();   								
								});
								</script>
			   					<?php
			   				}
			   			}
			   			
			   			?>			   			
			   		</td>
			   	</tr>
			</tbody>
		</table>
		
		</form>
	</div>
<?php
}elseif ($act=='update') {
	# code...
	$id_formula = (int) $_POST['id_formula'];
	$kode_formula = $_POST['kode'];
	$nama = $_POST['nama'];
	$satuan_terkecil = $_POST['satuan_terkecil'];
	$ket = $_POST['ket'];
	$satuan_per_karton = $_POST['satuan_per_karton'];
	$type = $_POST['type'];

	$kode_bb = $_POST['kode_bb'];
	$jumlah = $_POST['jumlah'];

	$id_formula_detail = $_POST['id_formula_detail'];

	$jmlData = count($kode_bb);
	
	if(!empty($id_formula)){
		$update = mysql_query("UPDATE tb_formula SET kode='$kode_formula', nama='$nama', satuan_terkecil='$satuan_terkecil', ket='$ket', type='$type', satuan_per_karton='$satuan_per_karton' WHERE id_formula='$id_formula'");

		if($update){
			for ($i=0; $i < $jmlData; $i++) { 
				
				$dataBB = mysql_fetch_array(mysql_query("SELECT satuan FROM tb_bb WHERE kode_bb='$kode_bb[$i]' LIMIT 1"));
				$satuan = $dataBB['satuan'];
	
				if(!empty($kode_bb[$i]) && !empty($jumlah[$i]) && !empty($id_formula_detail[$i])){
					$updateDetail = mysql_query("UPDATE tb_formula_detail SET kode_bb='$kode_bb[$i]', jumlah='$jumlah[$i]', satuan='$satuan' WHERE id_formula_detail='$id_formula_detail[$i]' ");
				}else{
					$insertDetail = mysql_query("INSERT INTO tb_formula_detail VALUES(NULL, '$id_formula', '$kode_bb[$i]', '$jumlah[$i]', '$satuan')");
				}					
			}
		}

		if($updateDetail || $insertDetail)
			sukses('Data berhasil disimpan', "?pages=formula&act=edit&id=$id_formula");
	}else{
		$insert = mysql_query("INSERT INTO tb_formula VALUES(NULL, '$kode_formula', '$nama', '$satuan_terkecil', '$satuan_per_karton', '$type', '$ket')");

		if($insert){
			$sqlFormula = mysql_query("SELECT id_formula FROM tb_formula ORDER BY id_formula DESC LIMIT 1");
			$latestFormula = mysql_fetch_array($sqlFormula);
			$id_formula = $latestFormula['id_formula'];


			for ($i=0; $i < $jmlData; $i++) { 
				$dataBB = mysql_fetch_array(mysql_query("SELECT satuan FROM tb_bb WHERE kode_bb='$kode_bb[$i]' LIMIT 1"));
				$satuan = $dataBB['satuan'];
				
				if(!empty($kode_bb[$i]) && !empty($jumlah[$i]))
					$insertDetail = mysql_query("INSERT INTO tb_formula_detail VALUES(NULL, '$id_formula', '$kode_bb[$i]', '$jumlah[$i]', '$satuan')");
			}
		}

		if($insertDetail)
			sukses('Data berhasil disimpan', '?pages=formula');
	}
	
}elseif ($act=='del') {
	# code...
	$id_formula = (int) filter($_GET['id']);

	$delete = mysql_query("DELETE FROM tb_formula_detail WHERE id_formula=$id_formula");

	$delete2 = mysql_query("DELETE FROM tb_formula WHERE id_formula=$id_formula");

	if($delete && $delete2)
		sukses('Data berhasil dihapus', '?pages=formula');
}elseif ($act=='delDetail') {
	# code...
	$id_formula = (int) filter($_GET['id2']);
	$id_formula_detail = (int) filter($_GET['id']);

	$delete = mysql_query("DELETE FROM tb_formula_detail WHERE id_formula_detail=$id_formula_detail");

	if($delete)
		sukses('Data berhasil dihapus', "?pages=formula&act=edit&id=$id_formula");

}
?>					

<link rel="stylesheet" href="css/chosen.css" />
<script src="js/chosen.jquery.js" type="text/javascript"></script>
<script type="text/javascript">
			function deleteAddress(e) {
				if($(e).parents(".tabelDetail").is('#detail_formula')){
					alert('Sisain satu ya..:p');
				}else{
					$(e).parents(".tabelDetail").remove();
				}
				
			}

			$(document).ready(function () {
				style_path = "css/colors";
				$('.dropdown-toggle').dropdown();
				//$("#date-picker").datepicker();

				//$("#box-tabs, #box-left-tabs").tabs();

				 $('.dropdown input, .dropdown label, .dropdown-menu').click(function(e) {
				    e.stopPropagation();
				 });

				  var cloneCount = 1;
				 $("#add_formula").click(function(e){
			         e.preventDefault();
				 	var clone = $('#detail_formula').clone().attr('id', 'detail_formula'+ cloneCount++).insertAfter($('[id^=detail_formula]:last'));
				 	clone.find('[type=text]').val('');	
				 	clone.find('[type=hidden]').val('');					 	
				 	$('#detail_formula'+(cloneCount-1)).find('.chzn-container').remove();
            		$('#detail_formula'+(cloneCount-1)).find('.chzn-select').removeClass('chzn-done').removeAttr('id').chosen();
            		
            		$('#detail_formula'+(cloneCount-1)).find('#chzn-selectx1').removeClass('chzn-done').removeAttr('id').chosen();
				 })

				$(".chzn-select").chosen();   
				

			});
			
</script>